/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Jul 2, 2012  7:13:44 PM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : apps.business.process.commons.customer
 * File Name : JavaThreadExample.java
 * TODO
 */
package apps.business.process.commons.customer;

import java.util.List;
import org.apache.log4j.Logger;
import jpa.entitys.synchro.staging.SdCustomerOutb1;
import sap.business.sd.outbound.VwSyncMktCustomerService;
import apps.promis.out.sales.VwSyncMktCustomerAction;

/**
 * @author chatree
 *
 */
public class JavaThreadExample extends Thread {
	
	private static final Logger log = Logger.getLogger(JavaThreadExample.class);
	private String customerCode = null;
	private JavaThreadExample(String customerCode){
		this.customerCode = customerCode;
	}
	
	private void processing(String customerCode) throws Exception{
		log.info("Sended Customer To SAP =============================================> Customer Code = " + customerCode);
		try{
			
			//Create to Staging
			List<SdCustomerOutb1> cus_lst = new VwSyncMktCustomerAction().CreateToStaging(customerCode); 
			
			//Send To SAP
			new VwSyncMktCustomerService().SendingToSAP(cus_lst);
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}					
	}
	 
    public void run()
    {
        //To store the number of Threads
        int count=0;
//        while(count<=9)
//        {
            //name=Thread.currentThread().getName();            
            //log.info(name);
            try {
            	
				processing(this.customerCode);
				sleep(500);
				
			} catch (Exception e) {
				log.error(e.getMessage());
				System.err.println(e.getMessage());
			}
//        }
    }
    
    public static void main(String[] args) throws Exception{
    	List<String> lst = new VwSyncMktCustomerAction().fincdCustomerAll();
		if(lst != null){
			if(lst.size() <= 8)
			{
				log.info("Customer = " + lst.size());
				for(String value : lst){
					//log.info("Sended Customer To SAP =============================================> Customer Code = " + value);
					try{
						//Create to Staging
						List<SdCustomerOutb1> cus_lst = new VwSyncMktCustomerAction().CreateToStaging(value);
						
						//Send To SAP
						new VwSyncMktCustomerService().SendingToSAP(cus_lst);
						
					}catch(Exception e){
						log.error(e.getMessage());
						System.err.println(e.getMessage());
					}
				}
    		}else
    		{	
    			int count = 0;
    	    	for(String value : lst){
    	    		count++;
    	    		new JavaThreadExample(value).start();
	            	
	            	if(count == 40){
	            		count = 0;
	            		sleep(2000);
	            	}
    	    	}
    		}
		}
	}
}
